﻿using System;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Windows.Forms;
using AppAcc.Models;
using AppAcc.Views.DanhMuc;

namespace AppAcc.Views.KTTSCD
{
    public partial class FormGiamTaiSanChinhSuaCT : DevComponents.DotNetBar.RibbonForm
    {
        private PhanMenKeToanEntities1 db = new PhanMenKeToanEntities1();
        //private AppAccContext db = new AppAccContext();
        public string idct = "";
        private int idctct = 0;
        private int indexrow = 0;
        private string listIdChiTietCanXoa = "";
        private int soRowXoa = 0;
        private bool kt = false;
        public FormGiamTaiSanChinhSuaCT()
        {
            InitializeComponent();
        }

        #region Event

        private void FormGiamTaiSanChinhSuaCT_Load(object sender, EventArgs e)
        {
            FillDataChungTu();
            if (idct != "")
            {
                var ct = db.ChungTus.Find(idct);
                txtSoChungTu.Text = ct.Id;
                txtSoChungTu.Enabled = false;
                txtSoChungTuGoc.Text = ct.SoChungTuGoc;
                txtNoiDung.Text = ct.NoiDung;
                cbbNhaCungCap.SelectedValue = ct.DoiTacId;
                cbbNhanVien.SelectedValue = ct.NhanVienId;
                dtiNgayChungTu.Value = ct.NgayChungTu;
                dtiNgayLapPhieu.Value = ct.NgayLapPhieu;
                GetDataChiTietChungTu();
                FillDataGridView();
                KiemTra();
                kt = true;
            }
            else
            {
                MessageBox.Show("Không tải được dữ liệu!");
                this.Close();
            }
        }

        private void bttThemMoi_Click(object sender, EventArgs e)
        {
            var f = new FormGiamTaiSanThemCT();
            f.ShowDialog();
            this.Close();
        }

        private void bttLuu_Click(object sender, EventArgs e)
        {
            Edit();
        }

        private void bttLuu_Thoat_Click(object sender, EventArgs e)
        {
            Edit();
            this.Close();
        }

        private void bttLuu_ThemMoi_Click(object sender, EventArgs e)
        {
            Edit();
            var f = new FormGiamTaiSanThemCT();
            f.ShowDialog();
            this.Close();
        }

        private void bttInChungTu_Click(object sender, EventArgs e)
        {
            Views.BaoCao.FormBaoCaoChungTuKeToan f = new BaoCao.FormBaoCaoChungTuKeToan(txtSoChungTu.Text);
            f.ShowDialog();
        }

        private void bttThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cbbNhaCungCap_SelectedIndexChanged(object sender, EventArgs e)
        {
            KiemTra();
        }

        private void cbbNhanVien_SelectedIndexChanged(object sender, EventArgs e)
        {
            KiemTra();
        }

        private void txtNoiDung_TextChanged(object sender, EventArgs e)
        {
            KiemTra();
        }

        private void dtiNgayLapPhieu_TextChanged(object sender, EventArgs e)
        {
            KiemTra();
        }

        private void dtiNgayChungTu_TextChanged(object sender, EventArgs e)
        {
            KiemTra();
        }

        private void bttThemMoiNhaCungCap_Click(object sender, EventArgs e)
        {
            var f = new FormDoiTac();
            f.ShowDialog();
        }

        private void bttThemMoiNhanVien_Click(object sender, EventArgs e)
        {
            var f = new FormNhanVien();
            f.ShowDialog();
        }

        private void dgvPhieuTSCDCT_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (kt == true)
            {
                KiemTra();
                UpdateAmount(e.ColumnIndex);
                MessageBox.Show(e.ColumnIndex.ToString());
            }
        }

        #endregion Event

        #region Metho

        private void KiemTra()
        {
            if (txtNoiDung.Text != "" && Convert.ToInt32(cbbNhaCungCap.SelectedValue) != 0 &&
                Convert.ToInt32(cbbNhanVien.SelectedValue) != 0 && dgvChungTuChiTiet.RowCount > 1 &&
                dtiNgayChungTu.Value.ToString().Length > 0 && dtiNgayLapPhieu.Value.ToString().Length > 0)
            {
                bttInChungTu.Enabled = true;
                bttLuu.Enabled = true;
                bttLuu_ThemMoi.Enabled = true;
                bttLuu_Thoat.Enabled = true;
            }
            else
            {
                bttInChungTu.Enabled = false;
                bttLuu.Enabled = false;
                bttLuu_ThemMoi.Enabled = false;
                bttLuu_Thoat.Enabled = false;
            }
        }

        private void FillDataChungTu()
        {
            cbbNhaCungCap.DataSource = db.DoiTacs.Where(t => t.NhomDoiTacId == 1).ToList();
            cbbNhaCungCap.DisplayMember = "TenDoiTac";
            cbbNhaCungCap.ValueMember = "Id";

            cbbNhanVien.DataSource = db.NhanViens.ToList();
            cbbNhanVien.DisplayMember = "TenNhanVien";
            cbbNhanVien.ValueMember = "Id";
        }

        private void FillDataGridView()
        {
            var n = dgvChungTuChiTiet.Columns["TaiKhoanNo"] as DataGridViewComboBoxColumn;
            if (n != null)
            {
                n.DataSource = db.TaiKhoans.ToList();
                n.DisplayMember = "Id";
                n.ValueMember = "Id";
            }

            var c = dgvChungTuChiTiet.Columns["TaiKhoanCo"] as DataGridViewComboBoxColumn;
            if (c != null)
            {
                c.DataSource = db.TaiKhoans.ToList();
                c.DisplayMember = "Id";
                c.ValueMember = "Id";
            }

            var n1 = dgvChungTuChiTiet.Columns["NhomThueHangHoaId"] as DataGridViewComboBoxColumn;
            if (n1 != null)
            {
                n1.DataSource = db.NhomThueHangHoas.Where(t => t.LoaiThue == 2).ToList();
                n1.DisplayMember = "TenThue";
                n1.ValueMember = "Id";
            }

            var n2 = dgvChungTuChiTiet.Columns["PhongBanId"] as DataGridViewComboBoxColumn;
            if (n2 != null)
            {
                n2.DataSource = db.PhongBans.ToList();
                n2.DisplayMember = "TenPhongBan";
                n2.ValueMember = "Id";
            }

            var n3 = dgvChungTuChiTiet.Columns["TaiSanId"] as DataGridViewComboBoxColumn;
            if (n3 == null) return;
            n3.DataSource = db.TaiSans.Where(t => t.TrangThai == 1).ToList();
            n3.DisplayMember = "TenTaiSan";
            n3.ValueMember = "Id";
        }

        private void CmsChenDong_Click(object sender, EventArgs e)
        {
            var dgwr = new DataGridViewRow();
            dgvChungTuChiTiet.Rows.Insert(indexrow, dgwr);
        }

        private void CmsXoaDong_Click(object sender, EventArgs e)
        {
            var row = dgvChungTuChiTiet.Rows[indexrow];
            var idrow = row.Cells["Id"].Value.ToString();
            listIdChiTietCanXoa += idrow + "-";
            row.Visible = false;
            soRowXoa += 1;
        }

        private void dgvPhieuTSCDCT_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Right) return;
            var ht = dgvChungTuChiTiet.HitTest(e.X, e.Y);
            var rowindex = ht.RowIndex; // get id chi tiet phieu tang tscd
            indexrow = rowindex;
            var row = dgvChungTuChiTiet.Rows[rowindex];
            idctct = Convert.ToInt32(row.Cells[0].Value);
            var rowcount = dgvChungTuChiTiet.RowCount;
            if (ht.ColumnIndex != -1 && ht.RowIndex == rowcount - 1)
            {
                var Menu = new ContextMenuStrip();
                //var chen = new ToolStripMenuItem("Chèn (Ins)"); //new button
                //chen.MouseDown += new MouseEventHandler(CmsChenDong_Click); // add event to button
                var xoa = new ToolStripMenuItem("Xóa (Del)");
                xoa.MouseDown += new MouseEventHandler(CmsXoaDong_Click);
                //Menu.Items.AddRange(new ToolStripItem[] {chen}); //add button to menu strip
                Menu.Items.AddRange(new ToolStripItem[] { xoa });
                dgvChungTuChiTiet.ContextMenuStrip = Menu;
            }
            else
                dgvChungTuChiTiet.ContextMenuStrip = null;
        }

        private void Edit()
        {
            var pt = db.ChungTus.Find(idct);
            pt.NgayChungTu = dtiNgayChungTu.Value;
            pt.SoChungTuGoc = txtSoChungTuGoc.Text;
            pt.NgayLapPhieu = dtiNgayLapPhieu.Value;
            pt.NhanVienId = Convert.ToInt32(cbbNhanVien.SelectedValue);
            pt.DoiTacId = Convert.ToInt32(cbbNhaCungCap.SelectedValue);
            pt.NoiDung = txtNoiDung.Text;
            pt.TrangThai = pt.TrangThai;
            int co = 0;
            decimal soTienNo = 0;
            decimal soTienCo = 0;
            pt.TongTien = 0;
            bool kt = true;
            foreach (DataGridViewRow item in dgvChungTuChiTiet.Rows)
            {
                if (co < dgvChungTuChiTiet.RowCount - soRowXoa)
                {
                    var ct = db.ChungTuChiTiets.Find(Convert.ToDecimal(item.Cells["Id"].Value));
                    ct.ChungTuId = pt.Id;
                    if (item.Cells["TaiKhoanNo"].Value != null && item.Cells["TaiKhoanNo"].Value.ToString().Length > 0)
                    {
                        ct.TaiKhoanNo = item.Cells["TaiKhoanNo"].Value.ToString();
                    }
                    else if (item.Cells["TaiKhoanCo"].Value != null &&
                             item.Cells["TaiKhoanCo"].Value.ToString().Length > 0)
                    {
                        ct.TaiKhoanCo = item.Cells["TaiKhoanCo"].Value.ToString();
                    }
                    if (item.Cells["TaiSanId"].Value != null && item.Cells["TaiSanId"].Value.ToString().Length > 0)
                    {
                        ct.TaiSanId = Convert.ToInt32(item.Cells["TaiSanId"].Value);
                    }
                    else
                    {
                        ct.TaiSanId = null;
                    }
                    if (item.Cells["SoTien"].Value != null && item.Cells["SoTien"].Value.ToString().Length > 0)
                    {
                        ct.SoTien = Convert.ToDecimal(item.Cells["SoTien"].Value);
                    }
                    else
                    {
                        ct.SoTien = 0;
                    }
                    if (item.Cells["PhongBanId"].Value != null && item.Cells["PhongBanId"].Value.ToString().Length > 0)
                    {
                        ct.PhongBanId = Convert.ToInt32(item.Cells["PhongBanId"].Value);
                    }
                    else
                    {
                        ct.PhongBanId = null;
                    }
                    if (item.Cells["NhomThueHangHoaId"].Value != null &&
                        item.Cells["NhomThueHangHoaId"].Value.ToString().Length > 0)
                    {
                        ct.NhomThueHangHoaId = Convert.ToInt32(item.Cells["NhomThueHangHoaId"].Value);
                    }
                    else
                    {
                        ct.NhomThueHangHoaId = null;
                    }
                    if (item.Cells["DienGiai"].Value != null && item.Cells["DienGiai"].Value.ToString().Length > 0)
                    {
                        ct.DienGiai = item.Cells["DienGiai"].Value.ToString();
                    }
                    else
                    {
                        ct.DienGiai = null;
                    }
                    if (ct.TaiKhoanNo != null)
                    {
                        soTienNo += Convert.ToDecimal(ct.SoTien);
                    }
                    else if (ct.TaiKhoanCo != null)
                    {
                        soTienCo += Convert.ToDecimal(ct.SoTien);
                    }
                    co++;
                    if (ct.TaiSanId != null)
                    {
                        var ts = db.TaiSans.Find(ct.TaiSanId);
                        ts.GiaTriKhauHao = 0;
                        ts.TrangThai = 0;
                        db.Entry(ts).State = EntityState.Modified;
                    }
                    db.Entry(ct).State = EntityState.Modified;
                }
            }
            pt.TongTien = soTienCo;
            if (soTienCo != soTienNo)
            {
                MessageBox.Show("Số phát sinh Nợ phải bằng số phát sinh Có!");
                kt = false;
            }
            if (soTienCo == 0 || soTienNo == 0)
            {
                MessageBox.Show("Dữ liệu không hợp lý!");
                kt = false;
            }
            if (soRowXoa > 0)
            {
                if (DeleteChungTuChiTiet() == false)
                {
                    kt = false;
                }
            }
            db.Entry(pt).State = EntityState.Modified;
            if (kt == true)
            {
                try
                {
                    db.SaveChanges();
                    MessageBox.Show("Chỉnh sửa thành công!");
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
        }
        bool DeleteChungTuChiTiet()
        {
            var rtm = false;
            if (listIdChiTietCanXoa.Length > 0)
            {
                var idtam = "";
                foreach (var i in listIdChiTietCanXoa)
                {
                    if (i.ToString() == "-")
                    {
                        var tam = Convert.ToDecimal(idtam);
                        var t = db.ChungTuChiTiets.Find(tam);
                        db.ChungTuChiTiets.Remove(t);
                        idtam = "";
                    }
                    else
                    {
                        idtam += i;
                    }
                }
                try
                {
                    db.SaveChanges();
                    rtm = true;
                }
                catch (Exception e)
                {
                    MessageBox.Show("Hệ thống gặp lỗi--" + e.Message);
                    rtm = false;
                    //throw;
                }
            }
            return rtm;
        }
        private void GetDataChiTietChungTu()
        {
            if (idct == "") return;
            dgvChungTuChiTiet.DataSource = db.ChungTuChiTiets.Where(t => t.ChungTuId == idct).ToList();
            dgvChungTuChiTiet.Refresh();
        }

        private void UpdateAmount(int index)
        {
            int counter;
            for (counter = 0; counter < (dgvChungTuChiTiet.Rows.Count - 1); counter++)
            {
                if (dgvChungTuChiTiet.Rows[counter].Cells["TaiKhoanNo"].Value == null &&
                    dgvChungTuChiTiet.Rows[counter].Cells["TaiKhoanCo"].Value == null) continue;
                var tkNo = Convert.ToInt32(dgvChungTuChiTiet.Rows[counter].Cells["TaiKhoanNo"].Value);
                var tkCo = Convert.ToInt32(dgvChungTuChiTiet.Rows[counter].Cells["TaiKhoanCo"].Value);

                if (tkNo > 0 && tkCo > 0)
                {
                    if (index == 2)
                    {
                        MessageBox.Show("Dữ liệu nhập không hợp lệ! Bạn chỉ co thể chọn 1 bên Nợ hoặc Có.");
                        dgvChungTuChiTiet.Rows[counter].Cells["TaiKhoanNo"].Value = null;
                    }
                    else if (index == 3)
                    {
                        MessageBox.Show("Dữ liệu nhập không hợp lệ! Bạn chỉ co thể chọn 1 bên Nợ hoặc Có.");
                        dgvChungTuChiTiet.Rows[counter].Cells["TaiKhoanCo"].Value = null;
                    }
                }
                else
                {
                    if (index == 0 || index == 1)
                    {
                        if (tkNo == 211)
                        {
                            dgvChungTuChiTiet.Rows[counter].Cells["TaiSanId"].ReadOnly = false;
                            dgvChungTuChiTiet.Rows[counter].Cells["PhongBanId"].ReadOnly = false;
                            dgvChungTuChiTiet.Rows[counter].Cells["SoTien"].ReadOnly = false;
                        }
                        else
                        {
                            dgvChungTuChiTiet.Rows[counter].Cells["TaiSanId"].ReadOnly = true;
                            dgvChungTuChiTiet.Rows[counter].Cells["PhongBanId"].ReadOnly = true;
                        }
                        if (tkNo == 133 || tkNo == 1331 || tkNo == 1332 || tkCo == 133 || tkCo == 1331 || tkCo == 1332 ||
                            tkCo == 621 || tkNo == 621)
                        {
                            dgvChungTuChiTiet.Rows[counter].Cells["NhomThueHangHoaId"].ReadOnly = false;
                            dgvChungTuChiTiet.Rows[counter].Cells["SoTien"].ReadOnly = false;
                        }
                        else
                        {
                            dgvChungTuChiTiet.Rows[counter].Cells["NhomThueHangHoaId"].ReadOnly = true;
                        }
                    }
                }
            }

        #endregion Metho
        }
    }
}